<template>
  <div>
    <div class="box">
      <!-- 头部form表单 -->
      <el-form
        :inline="true"
        :model="form"
        class="demo-form-inline form_top"
      >
        <el-form-item label="商品搜索:">
          <el-input v-model.trim="form.skuName" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            class="formbutton"
            @click="onSubmit"
          >查询</el-button>
        </el-form-item>
      </el-form>
      <!-- form表单下按钮 -->
      <div class="button_top">
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          class="formbutton buttonbodytop"
          @click="openDialog('新增')"
        >新建</el-button>
        <el-button type="primary" class="buttonbodyfoot" @click="opDialog">导入数据</el-button>
        <!-- table表格 -->
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          class="table_top"
          :header-cell-style="{ backgroundColor: '#f3f6fb', fontweight: 400 }"
        >
          <el-table-column prop="index" label="序号" width="60px" />
          <el-table-column prop="skuName" label="商品名称" width="150px" />
          <el-table-column prop="skuImage" label="商品图片">
            <template #default="{row}">
              <span class="box"> <img :src="row.skuImage" alt=""> </span>
            </template>
          </el-table-column>
          <el-table-column prop="brandName" label="品牌" />
          <el-table-column prop="unit" label="规格" />
          <el-table-column prop="price" label="商品价格" />
          <el-table-column prop="skuClass.className" label="商品类型" />
          <el-table-column prop="createTime" label="创建日期" />
          <el-table-column prop="address" label="操作" min-width="80px">
            <template #default="{row}">
              <el-button
                type="text"
                class="button_table_foot"
                @click="openDialog('修改' ,row)"
              >修改</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div v-if="totalPage !== '1'" class="foot">
          <p>共{{ totalCount }}条记录 第 {{ pageIndex }} / {{ totalPage }} 页</p>
          <div class="foot_button">
            <el-button
              type="info"
              :class="{'foot_button_foot' : true , 'isgrey' :form.pageIndex === 1}"
              :disabled="form.pageIndex === 1"
              @click="previous"
            >上一页</el-button>
            <el-button
              type="info"
              :class="{'foot_button_foot' : true , 'isgrey' :pageIndex === totalPage}"
              :disabled="pageIndex === totalPage"
              @click="next"
            >下一页</el-button>
          </div>
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      :title="type + '商品'"
      :visible.sync="showDialog"
      width="50%"
      class="dialog"
      @close="closeDialog"
    >
      <el-form ref="form" :model="formDialog" :rules="rules" label-width="130px">
        <el-form-item label="商品名称:" prop="skuName">
          <el-input
            v-model="formDialog.skuName"
            placeholder="请选择"
            maxlength="15"
            show-word-limit
            style="width: 480px"
          />
        </el-form-item>
        <el-form-item label="品牌:" prop="brandName">
          <el-input
            v-model="formDialog.brandName"
            placeholder="请输入"
            maxlength="10"
            show-word-limit
            style="width: 480px"
          />
        </el-form-item>
        <el-form-item label="商品价格(元):" prop="price">
          <el-input-number v-model="formDialog.price" controls-position="right" placeholder="请输入" style="width: 480px" :min="0.01" :step="0.5" :precision="2" />
        </el-form-item>
        <el-form-item label="商品类型:" prop="classId">
          <el-select
            v-model="formDialog.classId"
            placeholder="请选择"
            style="width: 480px"
          >
            <el-option v-for="item in resList" :key="item.classId" :label="item.className" :value="item.classId" />
          </el-select>
        </el-form-item>
        <el-form-item label="规格:" prop="unit">
          <el-input
            v-model="formDialog.unit"
            placeholder="请输入"
            maxlength="10"
            show-word-limit
            style="width: 480px"
          />
        </el-form-item>
        <el-form-item label="商品图片:" prop="skuImage">
          <el-upload
            v-model="formDialog.skuImage"
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="UploadImg"
          >
            <img v-if="formDialog.skuImage" :src="formDialog.skuImage" class="avatar">
            <i v-else class="el-icon-upload avatar-uploader-icon" />
          </el-upload>
          <div style="color: #bac0cd">
            支持扩展名：jpg、png，文件不得大于100kb
          </div>
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="addOrEdit">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      title="数据导入"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <div class="dialogs">
        <span>标题 :</span>
        <el-button type="primary" class="button-dialog" icon="el-icon-upload2" @click="handleUpload">上传文件</el-button>
      </div>
      <p class="dialogs-text">支持扩展名：xls、xlsx，文件不得大于1M</p>
      <input
        ref="excel-upload-input"
        class="excel-upload-input"
        type="file"
        accept=".xlsx, .xls"
        @change="handleUploadExcel"
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFile">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCommodity, getCommodityList, addSp, updateSp, addFileList } from '@/api/commodity'
import COS from 'cos-js-sdk-v5'
export default {
  name: 'Tektor',
  components: {},
  data() {
    return {
      form: {
        pageIndex: 1,
        pageSize: 10,
        skuName: null,
        classId: null
      },
      pageIndex: null,
      totalCount: null,
      tableData: null,
      totalPage: null,
      showDialog: false,
      dialogVisible: false,
      formDialog: {
        skuName: null,
        skuImage: null,
        price: undefined,
        classId: null,
        unit: null,
        brandName: null
      },
      rules: {
        skuName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        skuImage: [{ required: true, message: '请上传', trigger: 'blur' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        classId: [{ required: true, message: '请输入商品类型名称', trigger: 'blur' }],
        unit: [{ required: true, message: '请输入商品规格名称', trigger: 'blur' }],
        brandName: [{ required: true, message: '请输入品牌名称', trigger: 'blur' }]
      },
      resList: {},
      type: null,
      skuId: null,
      formData: null,
      loading: false
    }
  },
  created() {
    this.renderList()
  },
  methods: {
    onSubmit() {
      this.renderList()
    },
    openDialog(type, row) {
      console.log(row)
      console.log(row)
      this.type = type
      this.showDialog = true
      if (type === '修改') {
        this.skuId = row.skuId
        this.formDialog.skuName = row.skuName
        this.formDialog.skuImage = row.skuImage
        this.formDialog.price = row.price
        this.formDialog.classId = row.classId
        this.formDialog.unit = row.unit
        this.formDialog.brandName = row.brandName
      }
    },
    closeDialog() {
      Object.keys(this.formDialog).forEach(item => {
        this.formDialog[item] = null
      })
      this.formDialog.price = undefined
      this.$refs.form.resetFields()
      this.showDialog = false
    },
    async renderList() {
      this.loading = true
      const data = await getCommodity(this.form)
      this.totalCount = data.totalCount
      const res = data.currentPageRecords
      let num = 0
      res.forEach(item => {
        num++
        item.index = (data.pageIndex - 1) * 10 + num
        item.price = item.price / 100
        item.createTime = item.createTime.replace('T', ' ')
      })
      this.tableData = res
      const { currentPageRecords } = await getCommodityList()
      this.resList = currentPageRecords
      this.totalPage = data.totalPage
      this.pageIndex = data.pageIndex
      this.loading = false
    },
    next() {
      this.form.pageIndex += 1
      if (this.form.pageIndex > this.totalPage) {
        this.form.pageIndex = this.totalPage
      }
      this.renderList()
    },
    previous() {
      this.form.pageIndex -= 1
      if (this.form.pageIndex < 1) {
        this.form.pageIndex = 1
      }
      this.renderList()
    },
    async  addOrEdit() {
      try {
        if (this.type === '新增') {
          await addSp(this.formDialog)
        } else {
          await updateSp({ ...this.formDialog, skuId: this.skuId })
        }
        this.$message({
          type: 'success',
          message: `${this.type}成功`,
          offset: 60
        })
        this.renderList()
        this.closeDialog()
      } catch (error) {
        this.$message({
          message: '操作错误',
          offset: 60,
          type: 'error'
        })
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/png'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过100kb!')
      }
      return isJPG && isLt2M
    },
    // 上传头像
    UploadImg(data) {
      console.log(data)
      // 密钥
      const cos = new COS({
        SecretId: 'AKIDSqDSUJ7mDPLILMqQDyqcrzxmXSSPbm4H',
        SecretKey: 'KPPOIE6ztd9hAYtBXizynvx5HRabUEkb'
      })
      cos.putObject(
        {
          Bucket: 'zcy-1318643425', // 存储桶名称
          Region: 'ap-nanjing', // 地域名称
          Key: data.file.name, // 文件名称
          StorageClass: 'STANDARD', // 固定值
          Body: data.file // 文件对象
        },
        (err, data) => {
          if (err) {
            this.$message.error(err.Message)
          }
          if (data.statusCode === 200 && data.Location) {
            this.formDialog.skuImage = 'https://' + data.Location
          }
          console.log(data)
        }
      )
    },
    opDialog() {
      this.dialogVisible = true
    },
    handleClose() {
      this.dialogVisible = false
    },
    handleUpload() {
      this.$refs['excel-upload-input'].click()
    },
    handleUploadExcel(event) {
      const files = event.target.files
      console.log(event)
      console.log(files)
      if (files.length > 0) {
        const formData = new FormData()
        formData.append('fileName', files[0])
        this.formData = formData
      }
    },
    async  addFile() {
      try {
        await addFileList(this.formData)
        this.dialogVisible = false
      } catch (error) {
        console.log(error)
      } finally {
        this.$refs['excel-upload-input'].value = ''
      }
    }
  }}
</script>

<style scoped lang="scss">
.box {
  margin: 10px 15px 0 15px;
  .demo-form-inline.form_top {
    height: 60px;
    background-color: #fff;
    padding-top: 11px;
    padding-left: 20px;
    .formbutton {
      background-color: #5f84ff;
    }
  }
  .button_top {
    margin-top: 15px;
    background-color: #fff;
    padding-left: 15px;
    padding-top: 15px;
    margin-bottom: 15px;
    .buttonbodytop {
      border: 0px;
      background-color: #ff883a;
    }
    .buttonbodyfoot {
      border: 0px;
      background-color: #fbf4f0;
      color: #655b56;
    }
    .table_top {
      margin-top: 15px;
      .button_table_foot {
        color: #5f84ff;
      }
      img{
        height: 30px;
        width: 30px;
        border-radius: 50%;
      }
      .box{
        position: absolute;
        top: 5px;
        left: 0;
        height: 30px;
        width: 30px;
        background-color: #f3f6fb;
        border-radius: 50%;
      }

    }
    .foot {
      display: flex;
      justify-content: space-between;

      margin-top: 40px;
      padding-left: 15px;
      padding-right: 15px;
      padding-bottom: 30px;
      p {
        color: #dbdfe5;
      }
      .foot_button {
        height: 30px;
        line-height: 30px;
        .foot_button_top {
          margin-right: 15px;
          border: 0px;
          background-color: #d5ddf8;
          color: #606266;
        }
        .foot_button_foot {
          border: 0px;
          background-color: #d5ddf8;
          color: #606266;
        }
      }
    }
  }
}
.dialogs{
  width: 300px;
  margin-left: 50%;
  transform: translateX(-50%);
  span {
    margin-right: 20px;
  }
  .el-dialog__footer{
    margin-right: 200px;
  }
.button-dialog {
      height: 35px;
      width: 200px;
      border: none;
      border-radius: 5px;
      color: #fff;
    }
}
.dialogs-text{
  margin-left: 60%;
  width: 280px;
  font-size: 14px;
  color: #bac0cd;
  transform: translateX(-50%);
}
 .dialog-footer {
    margin-right: 20px;
    text-align: center;
    margin-right: -20px;
    .el-button--default {
      background-color: #fbf4f0 !important;
      border: 1px solid #fbf4f0;
      color: #655b56;
      margin-left: -20px;
      margin-right: 20px;
    }
    .el-button--primary {
      background-color: #ff5e20 !important;
      border: 1px solid #ff5e20;
      margin-right:140px;
    }
  }
.el-form {
  margin-left: 20px;
  ::v-deep .el-form-item__label {
    font-weight: normal;
  }
  .avatar-uploader {
    width: 115px;
    height: 115px;
    border: 1px dashed #d9d9d9;
    background-color: #f3f6fb;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
    width: 115px;
    line-height: 115px;
  }
  .avatar {
    width: 115px;
    height: 115px;
    display: block;
  }
  .dialog-footer {
    margin-top: 20px;
    text-align: center;
    margin-right: -20px;
    .el-button--default {
      background-color: #fbf4f0 !important;
      border: 1px solid #fbf4f0;
      color: #655b56;
      margin-left: -20px;
      margin-right: 20px;
    }
    .el-button--primary {
      background-color: #ff5e20 !important;
      border: 1px solid #ff5e20;
    }
     .foot_button_foot {
          border: 0px;
          background-color: #d5ddf8;
          color: #606266;
        }
  }
}
   ::v-deep .el-dialog{
    border-radius: 10px;
  }
  .excel-upload-input {
    display: none;
    z-index: -9999;
  }
  .isgrey { background-color: #edf0f9 !important; color: #d8dde6 !important;
}
::v-deep .el-dialog__body {
  padding: 0 20px;
}
</style>
